<template>
  <!-- 设备管理 -->
  <div class="app-container">
    <!-- 搜索查询 -->
    <div class="form-container">
      <el-form ref="queryForm" :inline="true" label-width="80px" :model="filters">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="filters.name" clearable placeholder="" size="small" />
        </el-form-item>
        <el-form-item label="所在区域" prop="province">
          <el-cascader v-model="currentProvince" size="small" placeholder="请选择所在区域" :props="cityNormalizer" :options="cityOptions" clearable style="width: 100%" @change="changeCitySelect">
            <template slot-scope="{ data }">
              <span>{{ data.label }}</span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="设备类型" prop="equipmenType">
          <treeselect
            v-model="filters.equipmenType"
            style="width:199px"
            size="small"
            :normalizer="normalizer"
            :options="equipOption"
            placeholder="请选择设备类型"
            no-options-text="暂无数据"
            :clearable="false"
            clear-value-text=""
            @select="handleEquipmenType"
          />
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="filters.status" size="small" placeholder="请选择">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 高级设置一栏 start -->
        <el-form-item>
          <slot name="label">
            <i
              class="highLevelStyle"
              :class="
                highLevelSet === true
                  ? 'el-icon-arrow-up'
                  : 'el-icon-arrow-down'
              "
              @click="highLevelSet = !highLevelSet"
            />
          </slot>
        </el-form-item>
        <el-row v-if="highLevelSet">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <!--操作按钮-->
    <div class="btns-group">
      <el-button id="Query" v-clickForbidden icon="el-icon-search" size="middle" @click="handleQuery">搜索</el-button>
      <el-button id="ResetQuery" v-clickForbidden icon="el-icon-refresh" size="middle" @click="resetQuery">重置</el-button>
      <el-button id="Add" v-hasPermi="['system:sysEquipment:add']" icon="el-icon-plus" size="middle" @click="handleAdd">新增</el-button>
      <el-button id="Update" v-hasPermi="['system:sysEquipment:edit']" icon="el-icon-edit" size="middle" :disabled="editSingle" @click="handleUpdate">修改</el-button>
      <el-button id="Delete" v-hasPermi="['system:systemEquipment:updateStatus']" icon="el-icon-delete" size="middle" :disabled="single" @click="handleDelete">报废</el-button>
      <el-button v-hasPermi="['system:systemEquipment:detail']" icon="el-icon-zoom-in" size="middle" :disabled="single" @click="handleDetail">详情</el-button>
      <el-button v-hasPermi="['system:sysEquipment:getRentalEquipments']" icon="el-icon-tickets" size="middle" @click="leaseEquipment">租赁设备</el-button>
      <el-button v-hasPermi="['system:sysEquipment:account']" icon="el-icon-tickets" size="middle" @click="UserEquipment">用户设备</el-button>
    </div>
    <!-- 表格展示start -->
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="tableData"
      :row-style="rowClass"
      style="width: 100%;"
      stripe
      class="table-list"
      :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
        (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
      @selection-change="handleSelectionChange"
      @row-click="rowChecked"
    >
      <el-table-column type="selection" width="38" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column
        prop="equipmentNum"
        label="设备编号"
        :show-overflow-tooltip="true"
        min-width="150"
        align="center"
      />
      <el-table-column
        prop="name"
        :show-overflow-tooltip="true"
        label="设备名称"
        min-width="150"
        align="center"
      />
      <el-table-column prop="equipmentModel" label="设备型号" min-width="120" align="center" />
      <el-table-column
        prop="typeName"
        label="设备类型"
        min-width="120"
        align="center"
      />
      <el-table-column prop="status" label="设备状态" width="120" align="center">
        <template slot-scope="{row}">
          <span v-if="row.status === '0'">正常</span>
          <span v-if="row.status === '1'">报废</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格展示end-->

    <!-- 分页器 -->
    <pagination
      class="pagination-container"
      :total="total"
      :page.sync="filters.pageNum"
      :limit.sync="filters.pageSize"
      @pagination="getList"
    />
    <!-- 企业信息新增修改组件start -->
    <addDialog ref="addDialog" :equip-option="equipOption" />
    <!-- 企业信息详情组件start -->
    <detailDialog ref="detailDialog" :equip-option="equipOption" />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listRegionTree } from '@/api/common/area.js'
import { listNoPermission } from '@/api/superviseBaseInfo/typeManage/equipmentType'
import { listEquipment, updateStatus } from '@/api/system/equipment'
import addDialog from './components/addDialog'
import detailDialog from './components/detailDialog'
import { mapState } from 'vuex'
export default {
  name: 'SupplierEquipment',
  components: {
    addDialog,
    detailDialog,
    Treeselect
  },

  data() {
    return {
      equipOption: [], // 设备类型
      // 筛选条件
      highLevelSet: false, // 高级设置显示隐藏
      filters: {
        pageNum: 1,
        pageSize: 20,
        name: '',
        equipmenType: undefined,
        province: '',
        city: '',
        county: '',
        status: '0',
        equipmenTypeId: ''
      },
      statusOptions: [
        { value: '0', label: '正常' },
        { value: '1', label: '报废' }
      ],
      // 选择的城市
      currentProvince: '',
      cityOptions: [], // 城市数据
      cityNormalizer: {
        value: 'value',
        label: 'label',
        children: 'children'
      },
      // 设备类型
      normalizer(node) {
      // 去掉children=null的属性
        if (node.children == null) {
          delete node.children
          return {
            id: node.typeNum,
            label: node.typeName
          }
        } else {
          return {
            id: node.typeNum,
            label: node.typeName,
            children: node.children
          }
        }
      },
      /* 列表 start*/
      // 日期范围
      dateRange: [],
      total: 0, // 分页总条数
      single: true, // 非单个禁用
      selectRow: [], // 高亮样式
      multipleSelection: [], // 选中表格行
      loading: false, // 列表加载
      tableData: [] // 表格数据
      /* 列表 end*/
    }
  },
  computed: {
    ...mapState({
      needTagsView: (state) => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    },
    editSingle() {
      const multip = this.multipleSelection
      return multip.length === 0 || multip[0].status === '2' || multip[0].equipmentJurisdiction === '0'
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.filters = { ...this.filters, ...this.$route.query }
    })
    this.getEquipmentType()
    this.getList()
    this.getRegionTree()
  },
  methods: {
    handleEquipmenType(value) {
      this.filters.equipmenTypeId = value.id
    },
    // 获取区域树
    async getRegionTree() {
      const { data } = await listRegionTree({ regionCode: '' })
      if (data) this.cityOptions = data
    },
    // 所属区域
    changeCitySelect(regionCode) {
      const [province, city, county] = regionCode
      this.filters.province = province // 省
      this.filters.city = city// 市
      this.filters.county = county // 区/县
    },
    // 获取设备类型
    async getEquipmentType() {
      const { data: { rows }} = await listNoPermission()
      this.equipOption = rows
    },
    // 获取数据
    async getList() {
      this.loading = true
      try {
        const { data: { rows, total }} = await listEquipment(this.changeDateRange(this.filters, this.dateRange))
        this.tableData = rows
        this.total = total
        // this.addTaleData()
        this.loading = false
      } catch {
        this.loading = false
      }
    },
    // list表格填充空白行
    addTaleData() {
      if (this.tableData.length < this.fristPageSize) {
        const arr = {}
        this.tableData.push(arr)
        this.addTaleData()
      }
    },
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach((item) => {
          // 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        val = []
      }
      if (val.length === 1) {
        this.single = false
      } else {
        this.single = true
      }
      this.selectRow = []
      this.multipleSelection = val
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      }
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    },
    /* 按钮 Start */
    // 搜索方法
    handleQuery() {
      this.filters.pageNum = 1
      this.getList()
    },
    // 重置搜索
    resetQuery() {
      this.filters.equipmenTypeId = ''
      this.filters.province = ''
      this.filters.city = ''
      this.filters.county = ''
      this.currentProvince = ''
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增
    handleAdd() {
      this.$refs.addDialog.handleAdd('新增设备')
    },
    // 详情
    handleDetail() {
      this.$refs.detailDialog.handleAdd('设备详情', this.multipleSelection[0].id)
    },
    // 编辑
    handleUpdate() {
      this.$refs.addDialog.handleAdd('修改设备', this.multipleSelection[0].id)
    },
    // 租赁设备
    leaseEquipment() {
      this.$router.push({ path: '/resourceManage/leaseEquipment' })
    },
    // 企业下用户的设备
    UserEquipment() {
      this.$router.push({ path: '/resourceManage/userEquipment' })
    },
    // 删除
    handleDelete() {
      this.$confirm('确认要报废此设备吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.loading = true
          await updateStatus(this.multipleSelection[0].id)
          this.loading = false
          this.msgSuccess('设备报废成功！')
          this.getList()
        })
        .catch(() => {
          this.msgWarning('已取消删除')
        })
    }
  }
}
</script>

<style scoped lang="scss">
</style>

